package com.example.doc_searcher.controller;

import com.example.doc_searcher.searcher.DocSearcher;
import com.example.doc_searcher.searcher.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-02-11
 * Time: 16:06
 */
@RestController
@RequestMapping("/docSearch")
@Slf4j
public class DocSearcherController{
    private static DocSearcher docSearcher = new DocSearcher();//这里实例化对象后，直接就把构造好的索引加载到内存当中了。（DocSearcher中的构造方法）
    private ObjectMapper objectMapper = new ObjectMapper();
    @RequestMapping(value = "/searcher" , produces = "application/json;charset=utf-8")
    @ResponseBody
    public String search(@RequestParam("query") String query) throws JsonProcessingException {
        log.info("后端接收到参数query:{}",query);
        List<Result> results = docSearcher.search(query);
        return objectMapper.writeValueAsString(results);
    }
}
//public class DocSearcherController extends HttpServlet {
//    private static DocSearcher docSearcher = new DocSearcher();
//    private ObjectMapper objectMapper = new ObjectMapper();
//
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //1:解析请求，拿到搜索词query
//        String query = req.getParameter("query");
//        //2:校验参数
//        if(query == null || query == ""){
//            String msg = "你输入的参数非法，没有获取到query的值";
//            System.out.println(msg);
//            resp.sendError(404,msg);
//            return;
//        }
//        System.out.println("query:" + query);
//        //3：返回结果
//        List<Result> results = docSearcher.search(query);
//        resp.setContentType("application/json;character=utf-8");//指定响应体数据类型位json
//        //4:继续使用流对象，把java对象整成json进行传递
//        objectMapper.writeValue(resp.getWriter(),results);
//    }
//
//}
